<template>
  <div class="page">
    <navigation>{{ $t('修改密码') }}</navigation>
    <div class="xiugai">
      <ul>
        <li><input v-model="oldpassword" type="password" :placeholder="$t('请输入原密码')" /></li>
        <li>
          <input v-model="password" :type="watchpassword1 ? 'text' : 'password'" :placeholder="$t('请输入新的密码')" />
          <a href="javascript:;" @click="watchpassword1 = !watchpassword1"><i class="iconfont" :class="watchpassword1 ? 'icon-htmal5icon09' : 'icon-htmal5icon08'"></i></a>
        </li>
        <li>
          <input v-model="repassword" :type="watchpassword2 ? 'text' : 'password'" :placeholder="$t('请确认新的密码')" />
          <a href="javascript:;" @click="watchpassword2 = !watchpassword2"><i class="iconfont" :class="watchpassword2 ? 'icon-htmal5icon09' : 'icon-htmal5icon08'"></i></a>
        </li>
        <nuxt-link to="/forget-password">{{ $t('忘记密码') }}</nuxt-link>
      </ul>
      <a href="javascript:;" class="wancheng" @click="handleUpdatePassword">{{ $t('完成') }}</a>
    </div>
  </div>
</template>
<script>
import { mapActions } from 'vuex'
import { isPassword } from '@/utils/validate'
import navigation from '@/components/Navigation.vue'
export default {
  components: { navigation },
  data () {
    return {
      watchpassword1: false,
      watchpassword2: false,
      oldpassword: '',
      password: '',
      repassword: ''
    }
  },
  methods: {
    ...mapActions({
      updatePassword: 'auth/updatePassword'
    }),
    handleUpdatePassword () {
      if (this.loading) { return false }
      do {
        if (this.oldpassword === '') {
          this.errmsg = '原密码不能为空'
          break
        }
        if (this.password === '') {
          this.errmsg = '密码不能为空'
          break
        }
        if (!isPassword(this.password)) {
          this.errmsg = '密码由6-20个数字、26个英文字母或者下划线组成'
          break
        }
        if (this.repassword === '') {
          this.errmsg = '确认密码不能为空'
          break
        }
        if (this.password !== this.repassword) {
          this.errmsg = '两次密码输入不一致'
          break
        }
      } while (false)
      if (this.errmsg) {
        this.$toast.error(this.errmsg)
        this.errmsg = ''
        return
      }
      const payload = {
        oldpassword: this.oldpassword,
        password: this.password,
        repassword: this.repassword
      }
      this.loading = true
      this.updatePassword(payload)
        .then((data) => {
          this.$toast.success(data.message)
          this.$router.back()
        })
        .catch((data) => {
          this.$toast.error(data.message)
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
</script>
